package pikes.peak.test;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.util.WebUtils;

import pikes.util.Assert;

public class PikesPeakTestRequest {

	private RequestContext requestContext = null;

	public PikesPeakTestRequest(final MessageSource messageSource, final MessageSource themeMessageSource,
			final LocaleResolver localeResolver, final ThemeResolver themeResolver) {
		this(messageSource, themeMessageSource, localeResolver, themeResolver, "/countries");
	}

	public PikesPeakTestRequest(final MessageSource messageSource, final MessageSource themeMessageSource,
			final LocaleResolver localeResolver, final ThemeResolver themeResolver, final String requestURI) {

		Assert.notNull(messageSource);
		Assert.notNull(localeResolver);

		DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
		beanFactory.registerSingleton(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, messageSource);

		MockThemeSource themeSource = new MockThemeSource();
		themeSource.addTheme(new MockTheme("myTheme", themeMessageSource));

		beanFactory.registerSingleton("themeSource", themeSource);

		MockServletContext servletContext = new MockServletContext();
		servletContext.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, Boolean.FALSE.toString());

		GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(beanFactory);
		webApplicationContext.setServletContext(servletContext);
		webApplicationContext.refresh();

		MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", requestURI);

		request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
		request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, themeResolver);
		request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, localeResolver);
		request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, webApplicationContext);
		request.setContextPath("/countries");

		requestContext = new RequestContext(request);
	}

	public final RequestContext getRequestContext() {
		return requestContext;
	}

}




